// src/stores/themeStore.js
import { defineStore } from "pinia";
import { ref, watchEffect } from "vue";

export const useThemeStore = defineStore("theme", () => {
  const isDark = ref(false);

  // 从本地存储初始化
  if (typeof localStorage !== "undefined") {
    isDark.value = localStorage.getItem("theme") === "dark";
  }

  // 监听系统偏好
  const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
  mediaQuery.addEventListener("change", (e) => {
    isDark.value = e.matches;
  });

  // 应用主题
  watchEffect(() => {
    if (isDark.value) {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
    } else {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
    }
  });

  const toggleTheme = () => {
    isDark.value = !isDark.value;
  };

  return { isDark, toggleTheme };
});
